#include <iostream>
#include <csignal>
#include <thread>
#include <chrono>

// Framework 核心
#include <framework/service_factory.h>
#include <framework/service_bus.h>
// Gateway 层
#include <gateway/include/http_server.h>

#include "services/ping_service/ping_service.h"
// 基础设施
#include "logger/LoggerManager.h"
#include "config/config.h"

using namespace cpp_backend;
using namespace cpp_backend::framework;
using namespace cpp_backend::gateway;
using namespace cpp_backend::config;
using namespace logger;

std::unique_ptr<HttpServer> g_http_server;
bool g_running = true;

void signalHandler(int signum)
{
    LOG_INFO << "Interrupt signal (" << signum << ") received.\n";
    g_running = false;
    if (g_http_server)
    {
        g_http_server->Stop();
    }
    ShutdownLogger();
}
bool InitializeLogger()
{
    try
    {
        LogConfig config{"ping_service_test"};
        InitLogger(config);
        LOG_INFO << "Logger initialized successfully.";
        return true;
    }
    catch (std::exception &e)
    {
        std::cout << "InitializeLogger error: " << e.what() << std::endl;
        return false;
    }
}
bool InitializePingService()
{
    LOG_INFO << "InitializePingService ..............";
    auto &bus = ServiceBus::Instance();
    auto ping_service = std::make_shared<services::PingService>();
    if (!ping_service->Initialize())
    {
        LOG_ERROR << "InitializePingService error";
        return false;
    }
    if (!ping_service->Start())
    {
        LOG_ERROR << "RegisterPingService error";
        return false;
    }
    if (!bus.RegisterService(ping_service))
    {
        LOG_ERROR << "RegisterPingService error";
        return false;
    }
    LOG_INFO << "InitializePingService success (version: " << ping_service->GetServiceVersion() << ")";
    return true;
}
bool InitializeHttpServer()
{
    LOG_INFO << "InitializeHttpServer ..............";
    try
    {
        auto &config = Config::Instance();
        config.LoadFromFile("server.json");
        const auto &server_config = config.GetServerConfig();

        g_http_server = std::make_unique<HttpServer>(server_config.host, server_config.http_port, server_config.thread_pool_size);
        g_http_server->RegisterRoute("/api/ping", "ping_service");
        g_http_server->RegisterRoute("/api/echo", "ping_service");
        g_http_server->RegisterRoute("/api/info", "ping_service");
        if (!g_http_server->Start())
        {
            LOG_ERROR << "InitializeHttpServer error -----------------";
            return false;
        }
        LOG_INFO << "HTTP sever started on: " << server_config.host << ":" << server_config.http_port;
        return true;
    }
    catch (std::exception &e)
    {
        LOG_ERROR << "InitializeHttpServer error: " << e.what();
        return false;
    }
}
/**
 * @brief 打印服务器信息
 */
void PrintServerInfo()
{
    auto &config = Config::Instance();
    const auto &server_config = config.GetServerConfig();

    std::cout << "\n";
    std::cout << "========================================\n";
    std::cout << "   PingService Test Server  \n";
    std::cout << "========================================\n";
    std::cout << "Version: 1.0.0\n";
    std::cout << "\n";
    std::cout << "HTTP Server: http://" << server_config.host << ":" << server_config.http_port << "\n";
    std::cout << "\n";
    std::cout << "Available APIs:\n";
    std::cout << "  GET  /api/ping         - 返回 pong (健康检查)\n";
    std::cout << "  GET  /api/echo?msg=xx  - 回显消息\n";
    std::cout << "  POST /api/echo         - 回显 JSON 请求体\n";
    std::cout << "  GET  /api/info         - 服务信息和统计\n";
    std::cout << "\n";
    std::cout << "前端调试示例:\n";
    std::cout << "  curl http://localhost:" << server_config.http_port << "/api/ping\n";
    std::cout << "  curl http://localhost:" << server_config.http_port << "/api/echo?msg=test\n";
    std::cout << "  curl -X POST http://localhost:" << server_config.http_port << "/api/echo \\\n";
    std::cout << "       -H 'Content-Type: application/json' \\\n";
    std::cout << "       -d '{\"test\":\"data\"}'\n";
    std::cout << "\n";
    std::cout << "按 Ctrl+C 停止服务器\n";
    std::cout << "========================================\n";
    std::cout << std::endl;
}
int main(int argc, const char *argv[])
{
    std::signal(SIGINT, signalHandler);
    std::signal(SIGTERM, signalHandler);
    LOG_INFO << "Starting PingService Test Server ...";
    if (!InitializeLogger())
    {
        LOG_ERROR << "InitializeLogger error";
        return -1;
    }
    // 2. 初始化 PingService
    if (!InitializePingService())
    {
        LOG_ERROR << "InitializePingService error";
        return -1;
    }
    if (!InitializeHttpServer())
    {
        LOG_ERROR << "InitializeHttpServer error";
        return -1;
    }
    // 打印服务器信息
    PrintServerInfo();
    LOG_INFO << "PingService Test Server started";
    while (g_running)
    {
        std::this_thread::sleep_for(std::chrono::seconds(1));
    }
    LOG_INFO << "Stopping PingService Test Server ...";
    if (g_http_server)
    {
        g_http_server->Stop();
    }
    ServiceBus::Instance().Clear();
    LOG_INFO << "PingService Test Server stopped";
    std::cout << "Goodbye!" << std::endl;
    return 0;
}